<template>
  <!-- 费用（条码申请项目） -->
  <div id="wLapplicationItem">
    <Splitpanes horizontal>
      <Pane size="55">
        <vxe-table ref="applicationItemTableList" v-loading="loading" border height="auto" :data="tableList" :footer-method="footerMethod" :merge-footer-items="[{ row: 0, col: 1, rowspan: 1, colspan: 5 }]" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
          isArrow: true,
          isTab: true,
          isEdit: true
        }" footer-row-class-name="table-footer" show-footer resizable show-overflow :menu-config="rightMenuConfig" @menu-click="contextMenuClickEvent">
          <!--          <vxe-column field="adviceCode" title="医嘱代号" width="120"></vxe-column>-->
          <!--          <vxe-column field="adviceName" title="医嘱名称" width="120"></vxe-column>-->

          <vxe-column field="isAddition" title="附" align="center" width="30">
            <template #default="{ row }">
              <el-tag :type="getIsStaticTagType(row)">{{ row.isAddition === 1 ? '是' : '否' }}</el-tag>
            </template>
          </vxe-column>
          <vxe-column field="feeCode" title="编号" width="100"></vxe-column>
          <vxe-column field="adviceId" title="申请号码" align="left" min-width="160"></vxe-column>
          <vxe-column field="feeName" title="收费项目" align="left" min-width="160"></vxe-column>
          <vxe-column field="amount" title="数量" width="80" align="right"></vxe-column>
          <vxe-column field="price" title="单价" width="80" align="right"></vxe-column>
          <vxe-column field="costs" title="金额" width="80" align="right"></vxe-column>
        </vxe-table>

      </Pane>
      <Pane size="45">
        <vxe-modal v-model="modalShow" id="specAdditionModal" width="600" height="250" show-zoom showFooter @hide="closeModal">
          <template #title>
            <span>添加附加条码</span>
          </template>
          <template #default>
            <vxe-form title-width="90" :data="specAdditionForm" title-align="right" span="23">
              <vxe-form-item title="条码号" field="iqcMaterialId">
                <template #default="{ data }">
                  <vxe-input ref="specInput" v-model="data.reqNo" placeholder="请输入条码号" @keydown.native.enter="saveSpecAddition" clearable></vxe-input>
                </template>
              </vxe-form-item>
            </vxe-form>
          </template>
          <template #footer>
            <vxe-button status="primary" @click="saveSpecAddition">保存</vxe-button>
          </template>
        </vxe-modal>
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button content="附加条码" status="primary" @click="addSpecAddition"></vxe-button>
            <vxe-button content="取消附加" status="danger" @click="removeSpecAddition"></vxe-button>
          </template>
        </vxe-toolbar>
        <div :style="{ height: '100%' }">
          <vxe-table ref="specAdditionListTable" v-loading="additionLoading" border height="auto" :data="specAdditionList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
            isArrow: true,
            isTab: true,
            isEdit: true
          }" resizable show-overflow>
            <vxe-column field="reqNo" title="条码号" width="160"></vxe-column>
            <vxe-column field="patId" title="病历号" width="160"></vxe-column>
            <vxe-column field="patNa" title="姓名" width="120"></vxe-column>
            <vxe-column field="sex" title="性别" width="40" align="center">
              <template #default="{ row }">
                {{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}
              </template>
            </vxe-column>
            <vxe-column field="reqTime" title="申请时间" width="120"></vxe-column>
            <vxe-column field="testPurpose" title="检验目的" min-width="120"></vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
  <!-- 知识库弹框 -->
  <vxe-modal v-model="showKnowledgeBase" id="showKnowledgeBase" class-name="showKnowledgeBase" width="100%" height="100%" min-width="460" min-height="300" destroy-on-close @hide="showKnowledgeBase = false">
    <template #title>
      <span>知识库</span>
    </template>
    <div style="width: 1000px; height: 100%; margin: 0 auto; background: #fff">
      <KnowledgeBase ref="knowledgeBaseRef"></KnowledgeBase>
    </div>
  </vxe-modal>
</template>
<script setup lang="ts">
import { getCurrentInstance, reactive, ref } from 'vue';
import { Pane, Splitpanes } from 'splitpanes';
import { IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import 'vxe-table/lib/style.css'
import { wkltByHisRightMenus } from "@/views/lab_sys/lab_bus/components/RptResultUtils";
import KnowledgeBase from '@/components/KnowledgeBaseByFee.vue';
import { log } from 'console';

let { proxy }: any = getCurrentInstance();

let reqNo = ref(''); //接收传过来的检验结果id
let rptGroup = ref(''); //接收传过来的检验结果id
let tableList = reactive([]);
let specAdditionList = reactive([]);
let loading = ref(false);
let additionLoading = ref(false);
let applicationItemTableList = ref(null);
let modalShow = ref(false);
let showKnowledgeBase = ref(false);
let knowledgeBaseRef: any = ref(null);

let isNotEdit = false;
let specAdditionForm = reactive({
  reqNo: '' //条码号)
}); //附加条码
let costTotal = ref(0.00);/**费用合计 */

defineExpose({
  getreqDetail,
  getCostTotal,
  cleanData
})

function cleanData() {
  tableList.length = 0;
}

// 页面加载列表
function getreqDetail(repData: any) {
  if (IsEmpty(repData) || !repData) {
    tableList.length = 0;
    return;
  }
  reqNo.value = '';
  if (!IsEmpty(repData.reqNo)) {
    reqNo.value = repData.reqNo;
  }
  if (!IsEmpty(repData.rptGroup)) {
    rptGroup.value = repData.rptGroup;
  }
  getDetail();
  getReqAdditions();
}

// 获取项目费用明细
function getDetail() {
  tableList.length = 0;
  loading.value = true;
  const url = '/api/reqdetail/findReqDetailByReqNo';
  proxy.$http
    .get(url, { params: { reqNo: reqNo.value } })
    .then(async (res: any) => {
      tableList.length = 0;
      loading.value = false;
      if (res.data && res.data.length > 0) {
        tableList.push(...res.data);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

//获取申请附加信息
function getReqAdditions() {
  specAdditionList.length = 0;
  additionLoading.value = true;
  const url = '/lab/reqMain/findLabReqAdditions';
  proxy.$http
    .get(url, { params: { reqNo: reqNo.value } })
    .then(async (res: any) => {
      additionLoading.value = false;
      if (res.data) {
        specAdditionList.push(...res.data);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 表尾
function footerMethod({ columns, data }) {
  let count = 0;
  tableList.forEach(item => {
    count += item.costs ? parseFloat(item.costs) : 0;
  });
  costTotal.value = count;
  return [
    columns.map((column, _columnIndex) => {
      if (_columnIndex === 1) {
        return `金额合计: ${formatJe(count)}`;
      }
      return null;
    })
  ];
}
/**主界面获取费用合计 */
function getCostTotal() {
  return costTotal.value;
}
function formatJe(v) {
  if (Number.isNaN(v)) {
    return '';
  }
  return Number(v).toFixed(2);
}

function addSpecAddition() {
  modalShow.value = true;
}

function removeSpecAddition() {
  const $table = (proxy.$refs.specAdditionListTable as any).getCurrentRecord();

  if (IsEmpty($table)) {
    proxy.$XModal.message({
      content: '请选择需要取消的附加条码',
      status: 'error'
    });
  }
  const url = '/lab/reqMain/deleteReqAdditions';
  const data = {
    id: $table.id,
    reqNo: $table.reqNo
  };
  proxy.$http
    .get(url, { params: data })
    .then(async (res: any) => {
      additionLoading.value = false;
      modalShow.value = false;
      if (res.status.code === 400) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else {
        VxeMessage('取消附加条码成功', VxeNotifyType.success);
      }
      getReqAdditions();
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
  return;
}

// 设置行类名
function setRowClassName() {
  /*if (row.isAdditional) {
    return 'spec-addition';
  }*/
}

// 关闭弹框
function closeModal() {
  modalShow.value = false;
  specAdditionForm.reqNo = '';
}
// 获取是否静态的tag标记(绿/红)
function getIsStaticTagType(row: any) {
  if (row.isAddition === 0) {
    return 'success';
  } else {
    return 'danger';
  }
}

// 保存
function saveSpecAddition() {
  additionLoading.value = true;
  if (IsEmpty(reqNo.value)) {
    VxeMessage('当前检验主记录没有条码号', VxeNotifyType.error);
  }
  if (IsEmpty(specAdditionForm.reqNo)) {
    VxeMessage('请输入附加条码号', VxeNotifyType.error);
  }
  const url = '/lab/reqMain/addReqAdditions';
  const data = {
    rptGroup: rptGroup.value,
    reqNo: reqNo.value,
    additionReqNo: specAdditionForm.reqNo
  };
  proxy.$http
    .get(url, { params: data })
    .then(async (res: any) => {
      additionLoading.value = false;
      modalShow.value = false;
      if (res.status.code === 400) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      } else {
        VxeMessage('附加条码成功', VxeNotifyType.success);
      }
      getReqAdditions();
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

const rightMenuConfig = ref(
  wkltByHisRightMenus(proxy, ({ options, column, row }) => {
    if (applicationItemTableList.value) {
      applicationItemTableList.value?.setCurrentRow(row);
      applicationItemTableList.value?.focus();
      //handleRowClick({ row });
    }
    const isDisabled = !column;
    options.forEach((list: any) => {
      list.forEach((item: any) => {
        item.disabled = isDisabled;
      });
    });
  })
);
/**右键菜单事件
 * @param menu 菜单对象
 * @param row 右键行对象
 * @param column 右键列对象
 */
function contextMenuClickEvent({ menu, row, column }) {
  switch (menu.code) {
    case 'knowledgeBase':
      getKnowledgeBaseData(row);
    default:
      break;
  }
}
// 获取知识库数据
function getKnowledgeBaseData(row) {
  showKnowledgeBase.value = true;
  proxy.$nextTick(() => {
    knowledgeBaseRef.value?.findKnowledgeBaseByAnsList(row);

  })
}

</script>
<style lang="scss" scoped>
#wLapplicationItem {
  height: 100%;
}
</style>